package com.app.sdnotepad;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;



import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
//import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;



public class NPEditMain extends Activity {

	// Menu item IDs
    public static final int MENU_ITEM_FILENAME = Menu.FIRST;
    public static final int MENU_ITEM_EXIT = Menu.FIRST + 1;
	
	EditText noteEdit = null;
	TextView noteView = null;
	TextView nameTextView = null;
	String fileName = null;
	String noteString = null;
	boolean flagModify = true;
	boolean flagFileExist = false;
	int flagEditOrView = 0;
	int noteLen = 10000;
	Intent getIntent = null;
	
	/**********************
	 *  load view layout 
	 *  ******************/
	protected void loadViewLayout()
	{
		BufferedReader noteReadBuf;
		
		this.setContentView(R.layout.viewmain);
		nameTextView = (TextView) findViewById(R.id.FilenameViewTextView);
		nameTextView.setText(fileName);
		noteView = (TextView) findViewById(R.id.TextViewViewNote);
		
		
		/* read text from file, store in noteChars */
		try 
		{
			noteReadBuf = new BufferedReader(new FileReader("/sdcard/app/note/"+fileName));
			while (true)
			{
				String tempStr = null;
				tempStr = noteReadBuf.readLine();
				if (tempStr == null)
				{
					break;
				}
				//noteChars.append(tempStr);
				noteView.append(tempStr);
				noteView.append("\n");
			}
			
			noteReadBuf.close();
			
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		flagEditOrView = 2;
		flagFileExist = true;
	}
	
	protected void editFileName()
	{
		Intent startFileNameIntent = new Intent();
		startFileNameIntent.setClass(this, NPTitleEditor.class);
		startFileNameIntent.putExtra("FILENAME", fileName);
		//startActivity(startFileNameIntent);
		startActivityForResult(startFileNameIntent, 1);
	}
	
	/**********************
	 *  handler for save to file function 
	 *  ******************/
	public void clickSave(View view)
	{
		String pFileStr = null;
		if (flagModify == true)
		{
			try {
				/* open writer */
				if (fileName == null)
				{
					editFileName();
				}
				else
				{
					pFileStr = "/sdcard/app/note/" + fileName;
					
					BufferedWriter saveWriteBuf = new BufferedWriter(new FileWriter(pFileStr));
					Editable noteEditTable = noteEdit.getText(); // get text from EditText
					noteString = noteEditTable.toString(); // transfer to string
					
					noteLen = noteString.length();
					if (noteLen > 10000)
					{
						noteLen = 10000;
					}
					saveWriteBuf.write(noteString, 0, noteLen);
					saveWriteBuf.close(); // close writer
					flagModify = true;
					
					loadViewLayout();
				}
				
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		
		
	}
	
	/**********************
	 *  handler for give up & back to DIR main view
	 *  ******************/
	public void clickGiveUp(View view)
	{
		Intent backDirViewIntent = new Intent();
		backDirViewIntent.setClass(this, NPDirMain.class);
		startActivity(backDirViewIntent);
		this.finish();
	}
	
	/**********************
	 *  handler for edit the file currently view
	 *  ******************/
	public void clickEditit(View view)
	{
		this.setContentView(R.layout.editmain);
		nameTextView = (TextView) findViewById(R.id.FilenameViewTextView);
		nameTextView.setText(fileName);
		noteEdit = (EditText) findViewById(R.id.EditTextEditNote);
		
		noteEdit.setText(noteView.getText());
		flagEditOrView = 1;
	}

	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		String cmdString = null;
		
		super.onCreate(savedInstanceState);
		
		
		
		/* switch view based on received CMD string */
		getIntent = getIntent();
		cmdString = getIntent.getStringExtra("CMD");
		if (cmdString.compareTo("CMD_NEW_FILE") == 0) // create a new file
		{
			this.setContentView(R.layout.editmain);
			nameTextView = (TextView) findViewById(R.id.FilenameViewTextView);
			nameTextView.setText("NULL");
			noteEdit = (EditText) findViewById(R.id.EditTextEditNote);
			fileName = null;
			flagEditOrView = 1;
			flagFileExist = false;
		}
		else if (cmdString.compareTo("CMD_OPEN_FILE") == 0) // open an exist file
		{
			fileName = getIntent.getStringExtra("FILENAME");
			
			loadViewLayout();
			
		}
	
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		
		if (flagEditOrView == 2) // under view layout
		{
			menu.add(0, MENU_ITEM_FILENAME, 0, R.string.EditFileName);
		}
		
		return super.onCreateOptionsMenu(menu);
	}
	
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		super.onOptionsItemSelected(item);
		
		switch (item.getItemId())
		{
			case MENU_ITEM_FILENAME:
			{
				editFileName();
				break;
			}
			
			default:
			{
				break;
			}
		}
		
		return true;
	}
	
	@Override
	public void onBackPressed() {
		super.onBackPressed();
		if (flagModify == false)
		{
			clickGiveUp(null);
		}
		else
		{
			clickGiveUp(null);// TODO
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		
		if (resultCode == RESULT_CANCELED)
		{
			return ;
		}
		
		String cmdString = null;
		String oldFileName = fileName;
		String newFileName = null;
		cmdString = data.getStringExtra("CMD");
		if (cmdString.compareTo("CMD_NEW_FILENAME") == 0)
		{
			newFileName = data.getStringExtra("NEW_FILENAME");
			if (fileName == null || newFileName.compareTo(fileName) != 0) // different name
			{
				fileName = newFileName; // update file name
				switch (flagEditOrView)
				{
					case 1: // edit
					{
						clickSave(null);
						break;
					}
					case 2: // view
					{
						File oldFile = new File("/sdcard/app/note/"+oldFileName);
						File newFile = new File("/sdcard/app/note/"+newFileName);
						oldFile.renameTo(newFile);
						loadViewLayout();
						break;
					}
				}
			}
		}
	}
	
	

}
